<?php

/**
 *  矿机视频管理
 */

namespace app\admin\service;

use app\admin\model\MinerVideos as ModelMinerVideos;
use app\facade\Basic;
use think\facade\Db;
use app\admin\model\ProductMerge;

class MinerVideo extends BaseService
{

    /**
     *   获取枚举
     */
    public function getEnum($param)
    {
        $modelSeller = new ModelMinerVideos();
        $result = $modelSeller->getFieldEnum($param['field']);
        return Basic::data(0, 'ok', $result);
    }

    /**
     * 获取机型列表
     */
    public function getList($param)
    {
        $where[] = ['is_del', '=', 0];

        if (!empty($param['video_title'])) {
            $param['video_title'] = trim($param['video_title']);
            $where[] = ['video_title', 'like', '%' . $param['video_title'] . '%'];
        }

        /* 时间范围 */
        if (!empty($param['start_date']) && !empty($param['end_date'])) {
            $where[] = ['create_time', 'between', [$param['start_date'], $param['end_date']]];
        }

        /* 发布人 */
        if (!empty($param['creator'])) {
            $where[] = ['creator', '=', $param['creator']];
        }

        /* 机型 */
        if (!empty($param['model_id'])) {
            $where[] = ['model_id', '=', $param['model_id']];
        }

        /* 查询 */
        $result = ModelMinerVideos::with(['creator_name' => function ($query) {
            return $query->field('id,cname');
        }, 'model_name' => function ($query) {
            return $query->field('id,model_name');
        }, 'coverimage' => function ($query) {
            return $query->field('id,url,name');
        }, 'video' => function ($query) {
            return $query->field('id,url,name');
        }])
            ->where($where)
            //            ->field('id,model_id,video_title,youtube_vid,coverimage_id,video_id,showstate,init_shownumber,shownumber,create_time,creator,update_time,is_del')
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $param['pageSize'],
                'var_page' => 'pageIndex',
            ]);

        $data = $result->toArray();

        foreach ($data['data'] as $key => $value) {

            /* 负责人 */
            if (!empty($value['creator_name'])) {
                $data['data'][$key]['creator_name'] = $value['creator_name']['cname'];
            } else {
                $data['data'][$key]['creator_name'] = '';
            }

            if (isset($value['model_name'])) {
                $data['data'][$key]['model_name'] = $value['model_name']['model_name'];
            } else {
                $data['data'][$key]['model_name'] = '';
            }
            $data['data'][$key]['coverimage_url'] = '';

            if (!empty($value['youtube_vid'])) {
                /* youtube 视频 */
                $data['data'][$key]['video_url'] = 'https://www.youtube.com/watch?v=' . $value['youtube_vid'];
                $data['data'][$key]['coverimage_url'] = "https://cdn.minetheasic.com/vi/{$value['youtube_vid']}/maxresdefault.jpg?x-oss-process=image/resize,m_lfit,w_500,limit_0/quality,q_100";
            } elseif (!empty($value['video_id'])) {



                /* 上传的视频地址 */
                if (!empty($value['video'])) {
                    $data['data'][$key]['video_url'] = $value['video']['url'];
                    unset($data['data'][$key]['video']);
                } else {
                    $data['data'][$key]['video_url'] = '';
                }
            } else {
                $data['data'][$key]['video_url'] = '';
                $data['data'][$key]['coverimage_url'] = '';
            }
            /* 上传的封面 */
            if (!empty($value['coverimage'])) {
                $data['data'][$key]['coverimage_url'] = $value['coverimage']['url'];
                unset($data['data'][$key]['coverimage']);
            }
            #处理聚合商品ids
            $data['data'][$key]['pm_names'] = '';
            if (!empty($value['pm_ids'])) {
                $product_merge = Db::name('product_merge')->where('id', 'in', $value['pm_ids'])->where('is_del', 0)->column('productname');
                if (!empty($product_merge)) {
                    $data['data'][$key]['pm_names'] = implode(',', $product_merge);
                }
            }
        }

        return Basic::paginator(0, 'ok', $data);
    }


    /**
     *  修改矿机视频状态
     */
    public function status($param)
    {

        $result = ModelMinerVideos::where('id', '=', $param['id'])->find();

        if (!$result) {
            return Basic::data(1, '视频信息不存在');
        }

        $result->showstate = $param['showstate'];
        $result->update_time = date('Y-m-d H:i:s', time());

        if ($result->save()) {
            return Basic::data(0, '更新成功');
        } else {
            return Basic::data(1, '更新失败');
        }
    }


    /**
     * save
     */
    public function save($param)
    {

        if (!empty($param['youtube_vid']) && (!empty($param['video_id']))) {
            return Basic::data(1, 'Youtube ID 和 视频同时存在');
        } elseif (empty($param['youtube_vid']) && (empty($param['video_id']))) {
            return Basic::data(1, '视频信息不能为空');
        }

        $result = ModelMinerVideos::where('video_title', '=', $param['video_title'])->where('is_del', '=', 0)->find();

        if ($result) {
            return Basic::data(1, '视频标题已存在');
        }

        if (empty($param['video_id'])) {
            unset($param['video_id']);
        }
        if (empty($param['model_id'])) {
            unset($param['model_id']);
        }
        if (empty($param['publish_time'])) {
            unset($param['publish_time']);
        }
        if (empty($param['coverimage_id'])) {
            unset($param['coverimage_id']);
        }

        if (empty($param['init_shownumber'])) {
            unset($result->init_shownumber);
        }

        $data = $param;
        $data['create_time'] = date('Y-m-d H:i:s', time());


        $result = ModelMinerVideos::create($data);
        if ($result && $param['pmv_id']) {
            $this->handleProductMergePmvId($param['pmv_id'], $result->id);
        }

        if ($result && $param['smv_id']) {
            $this->handleProductMergeSmvId($param['smv_id'], $result->id);
        }



        if ($result) {
            $this->logger->logOperation($result->id, 'MinerVideo', '添加', '添加矿机视频');
            return Basic::data(0, '保存成功');
        } else {
            return Basic::data(1, '保存失败');
        }
    }


    /**
     *  修改机型
     */
    public function update($param)
    {

        if (!empty($param['youtube_vid']) && (!empty($param['video_id']))) {
            return Basic::data(1, 'Youtube ID 和 视频同时存在');
        } elseif (empty($param['youtube_vid']) && (empty($param['video_id']))) {
            return Basic::data(1, '视频信息不能为空');
        }

        $data = $param;
        $data['update_time'] = date('Y-m-d H:i:s', time());

        if (ModelMinerVideos::where('video_title', '=', $param['video_title'])->where('id', '<>', $param['id'])->where('is_del', '=', 0)->find()) {
            return Basic::data(1, '已存在');
        }

        $result = ModelMinerVideos::where('id', '=', $param['id'])->where('is_del', '=', 0)->find();
        if (!$result) {
            return Basic::data(1, 'ID 不存在');
        }

        foreach ($data as $key => $value) {
            $result->$key = $value;
        }

        if (empty($param['video_id'])) {
            unset($result->video_id);
        }
        if (empty($param['model_id'])) {
            unset($result->model_id);
        }
        if (empty($param['publish_time'])) {
            unset($result->publish_time);
        }

        if (empty($param['coverimage_id'])) {
            $result->coverimage_id = null;
        }

        if (empty($param['init_shownumber'])) {
            unset($result->init_shownumber);
        }
        $old_result = $this->detail(['id' => $param['id']])['data'];

        $old_pmv_id = $old_result['pmv_id'];
        $old_smv_id = $old_result['smv_id'];

        if ($result->save()) {
            if ($param['pmv_id'] || $old_pmv_id != $param['pmv_id']) {
                $this->handleProductMergePmvId($param['pmv_id'] ?? [], $result->id);
            }
            if ($param['smv_id'] || $old_smv_id != $param['smv_id']) {
                $this->handleProductMergeSmvId($param['smv_id'] ?? [], $result->id);
            }
            $this->logger->logOperation($result->id, 'MinerVideo', '修改矿机视频', '修改矿机视频');
            return Basic::data(0, '修改成功');
        } else {
            return Basic::data(1, '修改失败');
        }
    }


    /**
     *  获取详情
     */
    public function detail($param)
    {
        $result = ModelMinerVideos::with(['model_name' => function ($query) {}, 'creator_name' => function ($query) {
            return $query->field('id,cname');
        }, 'coverimage' => function ($query) {
            return $query->field('id,url,name');
        }, 'video' => function ($query) {
            return $query->field('id,url,name');
        }])
            ->where('id', '=', $param['id'])
            ->where('is_del', '=', 0)
            //            ->field('id,model_id,video_title,youtube_vid,coverimage_id,video_id,showstate,init_shownumber,shownumber,create_time,creator,update_time')
            ->find();

        if (!$result) {
            return Basic::data(1, '未找到');
        }

        $data = $result->toArray();



        /* 负责人 */
        if (isset($data['model_name'])) {
            $data['model_name'] = $data['model_name']['model_name'];
        } else {
            $data['model_name'] = '';
        }


        $data['video_url'] = '';
        $data['coverimage_url'] = '';


        if (!empty($data['youtube_vid'])) {
            /* youtube 视频 */
            $data['video_url'] = 'https://www.youtube.com/watch?v=' . $data['youtube_vid'];
            $data['coverimage_url'] = "https://cdn.minetheasic.com/vi/{$data['youtube_vid']}/maxresdefault.jpg?x-oss-process=image/resize,m_lfit,w_500,limit_0/quality,q_100";
        } else {

            /* 上传的视频封面 */
            if (isset($data['coverimage'])) {
                $data['coverimage_url'] = $data['coverimage']['url'];
            }
            /* 上传的视频地址 */
            if (isset($data['video'])) {
                $data['video_url'] = $data['video']['url'];
            }
        }

        /* 上传的视频 */
        $video = [];
        if (isset($data['coverimage'])) {
            $video[] = [
                'id' => $data['coverimage']['id'],
                'url' => $data['coverimage']['url'],
                'name' => $data['coverimage']['name'],
                'type' => 'image',
            ];
            unset($data['coverimage']);
        }

        if (isset($data['video'])) {
            $video[] = [
                'id' => $data['video']['id'],
                'url' => $data['video']['url'],
                'name' => $data['video']['name'],
                'type' => 'video'
            ];
            unset($data['video']);
        }

        $data['file'] = $video;
        if (isset($data['creator_name'])) {
            $data['creator_name'] = $data['creator_name']['cname'];
        } else {
        }
        $data['pm_names'] = '';
        if (!empty($data['pm_ids'])) {
            $data['pm_names']  = Db::name('product_merge')->where('id', 'in', $data['pm_ids'])->where('is_del', 0)->field('id,productname')->select()->toArray();
        }

        $product_merge_model = new ProductMerge();
        $data['pmv_id'] = $product_merge_model->where('pmv_id', '=', $data['id'])->where('is_del', 0)->column('id');
        $data['smv_id'] = $product_merge_model->whereRaw('FIND_IN_SET(?, smv_id)', [$data['id']])->where('is_del', 0)->column('id');

        if ($result) {
            return Basic::data(0, 'ok', $data);
        } else {
            return Basic::data(1, '获取失败');
        }
    }

    /**
     *   删除机型
     */
    public function delete($param)
    {
        $result = ModelMinerVideos::where('id', 'in', $param['ids'])->where('is_del', '=', 0)->select();

        if (!$result) {
            return Basic::data(1, '不存在');
        }

        if ($result) {
            $result = ModelMinerVideos::where('id', 'in', $param['ids'])->where('is_del', '=', 0)->update([
                'update_time' => date('Y-m-d H:i:s', time()),
                'is_del' => time()
            ]);

            if ($result) {
                $this->logger->logOperation($param['ids'], 'MinerVideo', '删除矿机视频', '删除矿机视频');
                return Basic::data(0, '删除成功');
            } else {
                return Basic::data(1, '删除失败');
            }
        } else {
            return Basic::data(1, '删除失败');
        }
    }

    /**
     * @describe 处理聚合商品pmv_id
     * @author: Bobo
     * @date: 2025-07-07 12:02:01 
     * @param [type] @required
     * @return Renderable
     */
    public function handleProductMergePmvId(array $pmv_id, int $miner_video_id)
    {
        $product_merge_model = new ProductMerge();
        $product_merge = $product_merge_model->where(function ($query) use ($pmv_id, $miner_video_id) {
            $query->where('id', 'in', $pmv_id)
                ->whereOr('pmv_id', '=', $miner_video_id);
        })->where('is_del', '=', 0)->select();
        if (!$product_merge) {
            return false;
        } else {
            foreach ($product_merge as $item) {
                if (!$item['pmv_id'] || $item['pmv_id'] != $miner_video_id) { // 如果pmv_id为空 或者 pmv_id不等于miner_video_id，则设置为miner_video_id
                    $item['pmv_id'] = $miner_video_id;
                } else { // 如果pmv_id不为空，则判断pmv_id是否等于miner_video_id
                    if ($item['pmv_id'] == $miner_video_id && !in_array($item['id'], $pmv_id)) {
                        $item['pmv_id'] = null;
                    } else {
                        continue;
                    }
                }
                $item->save();
            }
        }
        $this->clearCTerminalCache(6); // 清除C端产品缓存
        return true;
    }

    /**
     * @describe 处理聚合商品smv_id
     * @author: Bobo
     * @date: 2025-07-07 12:02:01 
     * @param [type] @required
     * @return Renderable
     */
    public function handleProductMergeSmvId(array $smv_id, int $miner_video_id)
    {
        $product_merge_model = new ProductMerge();
        $product_merge = $product_merge_model->where(function ($query) use ($smv_id, $miner_video_id) {
            $query->where('id', 'in', $smv_id)
                ->whereOr('', 'exp', "FIND_IN_SET({$miner_video_id}, smv_id) > 0");
        })->where('is_del', '=', 0)->select();


        if (!$product_merge) {
            return false;
        } else {
            foreach ($product_merge as $item) {
                if (!$item['smv_id']) {
                    $item['smv_id'] = $miner_video_id;
                } else {
                    $existing_smv_ids = explode(',', $item['smv_id']);
                    $existing_smv_ids = array_map('intval', $existing_smv_ids);

                    if (in_array($miner_video_id, $existing_smv_ids) && !in_array($item['id'], $smv_id)) {
                        // 移除 miner_video_id
                        $existing_smv_ids = array_filter($existing_smv_ids, function ($id) use ($miner_video_id) {
                            return $id != $miner_video_id;
                        });
                        $item['smv_id'] = empty($existing_smv_ids) ? null : implode(',', $existing_smv_ids);
                    } else if (!in_array($miner_video_id, $existing_smv_ids) && in_array($item['id'], $smv_id)) {
                        // 添加 miner_video_id
                        $existing_smv_ids[] = $miner_video_id;
                        $item['smv_id'] = implode(',', $existing_smv_ids);
                    } else {
                        continue;
                    }
                }
                $item->save();
            }
        }
        $this->clearCTerminalCache(6); // 清除C端产品缓存
        return true;
    }
}
